package com.hzy.oplus.hook.activity;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.hzy.oplus.hook.R;
import com.hzy.oplus.hook.bean.LoginData;
import com.hzy.oplus.hook.bean.LoginResult;
import com.hzy.oplus.hook.event.LoginEvent;
import com.hzy.oplus.hook.fragment.LoginDialogFragment;
import com.hzy.oplus.hook.utils.EncodeUtil;
import com.hzy.oplus.hook.utils.QRUtils;
import com.hzy.oplus.hook.utils.UrlConstants;
import com.hzy.oplus.hook.utils.UserUtils;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private ImageView mImageView;
    private ImageView mUserIcon;
    private TextView mRefreshButton;
    private TextView mTextName;
    private TextView mTextCode;
    private FloatingActionButton mExitButton;
    private boolean mIsLogin;
    private LoginData mLoginData;
    private AlertDialog mLogoutDialog;
    private View mTopLayout;
    private ExecutorService mThreadPool;
    private Runnable mGenTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = findViewById(R.id.qr_image);
        mRefreshButton = findViewById(R.id.refresh_qr);
        mExitButton = findViewById(R.id.button_exit);
        mTextName = findViewById(R.id.text_name);
        mUserIcon = findViewById(R.id.user_icon);
        mTextCode = findViewById(R.id.text_code);
        mTopLayout = findViewById(R.id.top_layout);
        mRefreshButton.setOnClickListener(v -> onBottomClick());
        mTopLayout.setOnClickListener(view -> onTopLayoutClick());
        mExitButton.setOnClickListener(view -> AppUtils.exitApp());
        EventBus.getDefault().register(this);
        loadLoginResult();
    }

    private void onTopLayoutClick() {
        if (mIsLogin) {
            mLogoutDialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.exit_dialog_title)
                    .setPositiveButton(R.string.button_ok, (dialogInterface, i) -> {
                        UserUtils.saveLoginData(null);
                        EventBus.getDefault().post(new LoginEvent());
                    })
                    .setNegativeButton(R.string.button_cancel, (dialogInterface, i) -> {
                    })
                    .create();
            mLogoutDialog.show();
        } else {
            LoginDialogFragment.showDialog(getSupportFragmentManager());
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onLoginFinished(LoginEvent event) {
        loadLoginResult();
    }

    private void loadLoginResult() {
        mTextCode.setText(UserUtils.getPassCode());
        LoginResult loginResult = UserUtils.loadLoginData();
        mIsLogin = false;
        if (loginResult != null) {
            mLoginData = loginResult.data;
            mIsLogin = loginResult.isLogin();
        }
        mRefreshButton.setText(mIsLogin ?
                R.string.refresh_qr : R.string.please_login_first);
        if (mIsLogin) {
            mTextName.setText(mLoginData.userName);
            if (!StringUtils.isTrimEmpty(mLoginData.headPhoto)) {
                try {
                    Picasso.get().load(mLoginData.headPhoto)
                            .placeholder(R.drawable.ic_user).into(mUserIcon);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            generateQrCodeAsync();
        } else {
            mTextName.setText("");
            mUserIcon.setImageResource(R.drawable.ic_user);
            mImageView.setImageBitmap(null);
        }
    }

    private void onBottomClick() {
        if (mIsLogin) {
            generateQrCodeAsync();
        } else {
            LoginDialogFragment.showDialog(getSupportFragmentManager());
        }
    }

    private void generateQrCodeAsync() {
        mTextCode.setText(UserUtils.getPassCode());
        if (mThreadPool == null) {
            mThreadPool = Executors.newSingleThreadExecutor();
        }
        if (mGenTask == null) {
            mGenTask = () -> {
                String passCode = UserUtils.fetchPassCode();
                String userId = mLoginData.id;
                String codeKey = EncodeUtil.encodeKey(userId,
                        passCode, "A", UrlConstants.APP_VERSION);
                LogUtils.e("UserId: " + userId
                        + "\nPassCode: " + passCode
                        + "\nCodeKey: " + codeKey);
                final Bitmap bitmap = QRUtils.generateQrImg(codeKey);
                mImageView.post(() -> mImageView.setImageBitmap(bitmap));
            };
        }
        mThreadPool.execute(mGenTask);
    }
}
